<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								客户对账单
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar ref="scrollbarRef" @scroll="handleScroll"
					:style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="客户账单编号" prop="billNumber">
									<el-input v-model="formData.billNumber" placeholder="自动生成无需填写" readonly type="text"
										clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="客户" prop="customer">
									<el-select @clear="selectClear('customer')" v-model="formData.customer"
										@change="(value:any)=>selectChange(value,'customer')" multiple ref="customer"
										clearable>
										<el-option v-for="item in customerOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="customerOption[customerIndex]?.color">
													<component :is="customerOption[customerIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{customerOption[customerIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="对账起始日" prop="startDate">
									<el-date-picker placeholder="请选择" style="width:100%;" v-model="formData.startDate"
										type="date" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="对账终止日" prop="endDate">
									<el-date-picker placeholder="请选择" style="width:100%;" v-model="formData.endDate"
										type="date" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="对账人" prop="statementPerson">
									<el-input placeholder="请填写" readonly v-model="formData.statementPerson" type="text"
										clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="账单创建日期" prop="billCreationDate">
									<el-date-picker placeholder="请选择" style="width:100%;"
										v-model="formData.billCreationDate" type="date" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="备注" prop="remark">
							<el-input v-model="formData.remark" type="text" clearable></el-input>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="8">
								<el-form-item label="本期应收金额" prop="currentReceivableAmount">
									<el-input v-model="formData.currentReceivableAmount" type="text"
										placeholder="自动计算结果" disabled clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="本期已收金额" prop="currentReceivedAmount">
									<el-input v-model="formData.currentReceivedAmount" type="text" placeholder="自动计算结果"
										disabled clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="本期待收金额" prop="currentPendingAmount">
									<el-input v-model="formData.currentPendingAmount" type="text" placeholder="自动计算结果"
										disabled clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item>
							<el-input type="text" ref="salesPerson" readonly clearable class="my1">
								<template #prefix>
									<div style="margin: 0;padding: 0;">
										<el-tabs v-model="activeName" @tab-click="handleClick" class="my">
											<el-tab-pane label="对账明细" name="order">
												<div class="flex-space-between"
													style="height: 48px;padding-left: 10px;">
													<el-text type="info" size="small">
														来自 <el-text type="primary" size="small">客户对账明细</el-text> 的数据
														共{{formData.tableData.length}}条
													</el-text>
													<el-text>
														<el-tooltip effect="light" :hide-after="50" content="创建"
															placement="top">
															<div class="my-a" @click="setTableData">
																<el-icon size="16px" color="#409EFF">
																	<CirclePlus />
																</el-icon>
															</div>
														</el-tooltip>
													</el-text>
												</div>
												<!--  -->
												<el-scrollbar style="width: calc(100vw - 48px - 32px);height: 300px;">
													<el-table @cell-dblclick="tableCellClick" v-loading="loading"
														:data="formData.tableData" :stripe="false" table-layout="auto"
														:default-sort="{}" border style="width: 100%;height: 300px;"
														class="my">
														<el-table-column width="76" fixed="left" prop="id"
															:sortable="false">
															<template #default="scope">
																<el-tooltip effect="light" :hide-after="50" content="复制"
																	placement="top">
																	<el-button style="padding: 0;" class="my"
																		@click="copyTableData(scope.$index)"
																		:icon="DocumentAdd"></el-button>
																</el-tooltip>
																<el-tooltip effect="light" :hide-after="50" content="删除"
																	placement="top">
																	<el-button style="padding: 0;" class="my"
																		@click="deleteTableData(scope.$index)"
																		:icon="Delete"></el-button>
																</el-tooltip>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="occurrenceDate"
															label="发生日期*(可选)" :sortable="false">
															<template #default="scope">
																<el-form-item v-if="!scope.row.occurrenceDate"
																	class="my"
																	:prop="`tableData[${scope.$index}].occurrenceDate`"
																	:rules="[{required: true,message: '发生日期必选',trigger: 'change'}]">
																	<el-input type="number" class="my-s"
																		v-model="scope.row.occurrenceDate" clearable
																		readonly></el-input>
																</el-form-item>
																<el-text
																	v-else>{{formatDate(scope.row.occurrenceDate)}}</el-text>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="productId" label="产品*(可选)"
															:sortable="false">
															<template #default="scope">
																<el-form-item v-if="!scope.row.productId" class="my"
																	:prop="`tableData[${scope.$index}].productId`"
																	:rules="[{required: true,message: '产品必选',trigger: 'change'}]">
																	<el-input type="number" class="my-s"
																		v-model="scope.row.productId" clearable
																		readonly></el-input>
																</el-form-item>
																<div class="flex-align-center" v-else>
																	<el-icon
																		:color="productOption?.filter(val=>val.value===scope.row.productId)[0]?.color">
																		<component
																			:is="productOption?.filter(val=>val.value===scope.row.productId)[0]?.icon">
																		</component>
																	</el-icon>
																	<el-text size="small" style="margin-left: 6px;">
																		{{productOption?.filter(val=>val.value===scope.row.productId)[0]?.label}}
																	</el-text>
																</div>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="salesOrderId" label="类型*(可选)"
															:sortable="false">
															<template #default="scope">
																<el-form-item v-if="!scope.row.salesOrderId" class="my"
																	:prop="`tableData[${scope.$index}].salesOrderId`"
																	:rules="[{required: true,message: '类型必选',trigger: 'change'}]">
																	<el-input type="number" class="my-s"
																		v-model="scope.row.salesOrderId" clearable
																		readonly></el-input>
																</el-form-item>
																<div class="flex-align-center" v-else>
																	<el-icon
																		:color="salesOrderOption?.filter(val=>val.value===scope.row.salesOrderId)[0]?.color">
																		<component
																			:is="salesOrderOption?.filter(val=>val.value===scope.row.salesOrderId)[0]?.icon">
																		</component>
																	</el-icon>
																	<el-text size="small" style="margin-left: 6px;">
																		{{salesOrderOption?.filter(val=>val.value===scope.row.salesOrderId)[0]?.label}}
																	</el-text>
																</div>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="totalAmount"
															label="本次对账总额*(可选)" :sortable="false">
															<template #default="scope">
																<el-form-item v-if="!scope.row.totalAmount" class="my"
																	:prop="`tableData[${scope.$index}].totalAmount`"
																	:rules="[{required: true,message: '对账总额必填',trigger: 'change'}]">
																	<el-input type="number" class="my-s"
																		v-model="scope.row.totalAmount" clearable
																		readonly></el-input>
																</el-form-item>
																<el-text>{{scope.row.totalAmount}}</el-text>
															</template>
														</el-table-column>
													</el-table>
												</el-scrollbar>
											</el-tab-pane>
										</el-tabs>
									</div>
								</template>
							</el-input>
						</el-form-item>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
			<!--  -->
			<levitation ref="levitationRef" :option="selectCell.option" :types="types" :st_type="selectCell.type"
				:params="levitationParams" :observerElement="scrollbarRef" :element="element" @change="levitationChange"
				@blur="levitationBlur" />
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import {List, UserFilled, WalletFilled, CirclePlus, DocumentAdd, Delete, UploadFilled, Upload, Download } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber } from '../../../utils';
	import { formatDate } from '../../../utils/date';
	import { useSelect } from '../../../utils/mixins';
	import { ElMessage, FormInstance } from 'element-plus';
	import levitation from '../../../components/levitation-form/levitation-form.vue';
	import { jwtDecode } from 'jwt-decode';
	import cookie from 'js-cookie';
	import { getShipments } from '../../../api/shipmentAPI';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);
	const activeName = ref('order');
	//levitation start
	const element = ref(null);
	const levitationRef = ref(null);
	const scrollbarRef = ref(null);
	const types = ref('');
	const selectCell = ref({
		id: 0,
		property: '',
		type: '',
		option: []
	});
	const levitationParams = ref(null);
	//levitation end

	// 表单
	const formData = ref({
		billNumber: null,//客户账单编号
		customerId: null,//客户
		customer: [],
		startDate: null,//对账起始日
		endDate: null,//对账终止日
		statementPerson: null,//对账人
		billCreationDate: null,//账单创建日期
		remark: null,//备注
		currentReceivableAmount: null,//本期应收金额
		currentReceivedAmount: null,//本期已收金额
		currentPendingAmount: null,//本期待收金额
		tableData: []//
	});
	//验证
	const rules = reactive({
		billNumber: [],//客户账单编号
		customer: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//客户
		startDate: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//对账起始日
		endDate: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//对账终止日
		statementPerson: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//对账人
		billCreationDate: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//账单创建日期
		remark: [],//备注
		currentReceivableAmount: [],//本期应收金额
		currentReceivedAmount: [],//本期已收金额
		currentPendingAmount: [],//本期待收金额
		tableData: []//
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//客户
	const customerOption = ref([]);
	const customerIndex = ref(-1);
	const customer = ref(null);
	//产品 table
	const productOption = ref([]);
	//类型
	const salesOrderOption = ref([]);
	//出库 table
	const outboundOption = ref([]);
	//入库 table
	const inboundOption = ref([]);
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getCustomerList();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			const token = cookie.get('token');
			const decodedToken : {
				username : string
			} = jwtDecode(token);
			// console.log('decodedToken--->', decodedToken);
			//
			formData.value.statementPerson = decodedToken?.username;
			//
			return true;
		}
		//
		const result = await request({
			url: '/SalesReceipt/selectCId',
			params: {
				customerStatementId: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		//
		formData.value = { ...result.data.t };
		formData.value.tableData = [...result.data.t.customerStatementDetails];
		//
		return true;
	}
	//设置一个
	const setTableData = () => {
		formData.value.tableData.push({
			id: +new Date(),
			occurrenceDate: null,//发生日期
			productId: null,//产品
			salesOrderId: null,//应收/应付明细(类型)
			totalAmount: null,//本次对账总额
			// outboundId: null,//出库
			// inboundId: null,//入库
		});
	}
	//复制一个
	const copyTableData = (index : number) => {
		//...
		const item = { ...formData.value.tableData[index] };
		item.id = +new Date();
		formData.value.tableData.push(item);
	}
	//删除一个
	const deleteTableData = (index : number) => {
		formData.value.tableData.splice(index, 1);
	}
	const selectClear = (type : string) => {
		formData.value[type] = [];
	}
	//点击单元格回调
	const tableCellClick = (row : any, column : any, cell : HTMLTableCellElement, event : Event) => {
		types.value = '';
		//发生日期
		if (column.property === 'occurrenceDate') {
			types.value = 'date';
		}
		//产品
		if (column.property === 'productId') {
			types.value = 'select-icon';
			selectCell.value.option = [...productOption.value];
		}
		//类型
		if (column.property === 'salesOrderId') {
			types.value = 'select-icon';
			selectCell.value.option = [...salesOrderOption.value];
		}
		//本次对账总额
		if (column.property === 'totalAmount') {
			types.value = 'number';
		}
		// //出库
		// if (column.property === 'outboundId') {
		// 	types.value = 'select-icon';
		// 	selectCell.value.option = [...outboundOption.value];
		// }
		// //入库
		// if (column.property === 'inboundId') {
		// 	types.value = 'select-icon';
		// 	selectCell.value.option = [...inboundOption.value];
		// }
		element.value = cell;
		//
		selectCell.value.id = row.id;
		selectCell.value.property = column.property;
		//
		levitationParams.value = row[column.property];
		setTimeout(() => {
			levitationRef.value.getElementInfo();
		}, 1);
		//
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'customer', //哪一个下拉框，根据ref
			option: customerOption, //下拉列表选项
			indexVar: customerIndex, //当前选中项
			idVar: 'customerId', //当前id值
			blurRef: customer, //ref
			fun: getSaleCustomerId
		},];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//获取客户
	const getCustomerList = async () => {
		const result = await request({
			url: '/SalesReceipt/selectCustomer',
		});
		console.log('getCustomerList --->', result);
		customerOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			customerOption.value.push({
				label: `${item.customerName}（${item.customerRating}）${item.billingMethod}`,
				value: item.customerId,
				icon: UserFilled,
				color: '#82b51b'
			});
			if (formData.value.customerId === item.customerId) {
				formData.value.customer = [item.customerId];
				customerIndex.value = key;
				//
				getSaleCustomerId(item.customerId);
			}
		});
	}
	//根据客户id获取
	const getSaleCustomerId = async (customerId : number) => {
		const result = await request({
			url: '/SalesReceipt/selectSaleCustomerId',
			params: { customerId }
		});
		//
		console.log('getSaleCustomerId --->', result);
		productOption.value = [];
		salesOrderOption.value = [];
		result.data.t.forEach(async (item : any, key : number) => {
			//产品
			productOption.value.push({
				label: `${item.product.productName}${item.product.model} | 在库${item.product.currentInventory}件`,
				value: item.product.productId,
				icon: UploadFilled,
				color: '#5283ff'
			});
			//类型
			salesOrderOption.value.push({
				label: `${item.dictData[1].dictLabel}_${formatDate(item.occurrenceDate)}`,
				value: item.receivablePayableDetailId,
				icon: List,
				color: '#5283ff'
			});
		});
	}
	//
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = { customerStatement: { ...formData.value }, customerStatementDetails: [...formData.value.tableData] };
				delete data.customerStatement.tableData;
				delete data.customerStatement.customer;
				let type = '';
				if (!route.query.id) {
					type = '/saveCustomerStatement';
				} else {
					type = '/updateCustomerStatement';
				}
				//
				const result = await request({
					url: '/SalesReceipt' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				// //
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//失去焦点 ***** 重要！重要！重要！
	const levitationBlur = () => {
		element.value = null;
	}
	//内容改变
	const levitationChange = (value : string | number) => {
		console.log('value --->', value);
		formData.value.tableData.forEach((item : any, key : number) => {
			console.log('item.id --->', item.id, 'selectCell.value.id --->', selectCell.value.id);
			if (item.id === selectCell.value.id) {
				item[selectCell.value.property] = value;
			}
		});
	}
	//滚动
	const handleScroll = (e : any) => {
		// console.log('handleScroll --->', e);
		if (element.value === null) return;
		levitationRef.value.getElementInfo();
	}
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-scrollbar__view {
		display: block !important;
	}

	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>